package main

import (
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"sanrenx.com/xyxf/app/routers"
	"sanrenx.com/xyxf/cron"
	"sanrenx.com/xyxf/pkg/gredis"
	"sanrenx.com/xyxf/pkg/logging"
	"sanrenx.com/xyxf/pkg/orm"
	"sanrenx.com/xyxf/pkg/setting"
	"sanrenx.com/xyxf/pkg/utils"
)

// @title Golang 修业学佛 API
// @version 1.0
// @description  Golang api of 修业学佛
// @termsOfService http://sanrenx.com

// @contact.name API Support
// @contact.url http://www.sanrenx.com
// @contact.email 767758350@qq.com
func main() {
	//解析命令行参数写入
	var env string
	flag.StringVar(&env, "e", "local", "运行环境，默认dev：开发环境")
	flag.Parse()
	//输出解析参数结果
	log.Printf("[info] 运行环境 env: %s\n", env)
	//设置开发模式 -e
	setting.Setup(env)
	logging.Setup()
	utils.Setup()
	orm.Setup()    //db
	gredis.Setup() //redis
	if setting.ServerSetting.RunMode == "prod" {
		gin.SetMode("release")
	} else {
		gin.SetMode("debug")
	}

	cron.Setup() //定时任务

	routersInit := routers.InitRouter()
	readTimeout := setting.ServerSetting.ReadTimeout
	writeTimeout := setting.ServerSetting.WriteTimeout
	endPoint := fmt.Sprintf(":%d", setting.ServerSetting.HttpPort)
	maxHeaderBytes := 1 << 20

	server := &http.Server{
		Addr:           endPoint,
		Handler:        routersInit,
		ReadTimeout:    readTimeout,
		WriteTimeout:   writeTimeout,
		MaxHeaderBytes: maxHeaderBytes,
	}

	log.Printf("[info] start http server listening %s", endPoint)

	err := server.ListenAndServe()
	if err != nil {
		logging.Error(err)
	}

	// If you want Graceful Restart, you need a Unix system and download github.com/fvbock/endless
	//endless.DefaultReadTimeOut = readTimeout
	//endless.DefaultWriteTimeOut = writeTimeout
	//endless.DefaultMaxHeaderBytes = maxHeaderBytes
	//server := endless.NewServer(endPoint, routersInit)
	//server.BeforeBegin = func(add string) {
	//	log.Printf("Actual pid is %d", syscall.Getpid())
	//}
	//
	//err := server.ListenAndServe()
	//if err != nil {
	//	log.Printf("Server err: %v", err)
	//}

}
